/*******************************************************************************
 *            SHOPPING CART COLLECTIONS CLASS EXTENDS COLLECTION CLASS
 ******************************************************************************/
function CartCollection() {};
//inherit from Collection class
CartCollection.prototype = new Collection();
//reset the contructor after inheritance
CartCollection.prototype.constructor = CartCollection;

//augmenting the prototype

//overwriting the inherited add function
CartCollection.prototype.add = function(key,value) {
    var self = this;
    if( typeof self.list[key] == 'undefined' ) {
        self.list[key] = {qty:1,data:value};
        self.size++;
    }
    else{
        var curr_qty = parseInt(self.list[key].qty);
        self.list[key].qty = curr_qty + 1;
    }
    self.fireCallbacks('add', key, value);
}

CartCollection.prototype.edit = function(key,value) {
    var self = this;
    for(var key_item in value){
        self.list[key].data[key_item] = value[key_item];
    }
    self.fireCallbacks('add', key, value);
}

//overwriting the inherited remove function
CartCollection.prototype.remove = function(key) {
    var self = this;
    if( typeof self.list[key] != 'undefined' ) {
        var curr_qty = parseInt(self.list[key].qty);
        self.list[key].qty = curr_qty - 1;
        var value = self.list[key];
        if(self.list[key].qty == 0){
            delete self.list[key];
            self.size--;
        }
        self.fireCallbacks('remove',key, value);
    }
}

//Create Data for SaleItem Model
CartCollection.prototype.createSaleItemModelData = function(params) {
    var self = this;
    var data = [];
    self.iterate(function(key,obj){
        var id = key;
        var name = obj.data.name;
        var initial_charge = parseFloat(obj.data.initial_charge);
        var additional_charge = parseFloat(obj.data.additional_charge);
        var quantity = obj.qty;
        var cost_price = self.getItemTotalCost(quantity,initial_charge,additional_charge);

		data.push({
            id:0,
            fee_type_id:id,
            amount:cost_price,
            academic_year:params['academic_year'],
            index_number:params['index_number'],
            trans_type_to_use:params['trans_type_to_use']
        });
    });

    return data;
}


CartCollection.prototype.getTotalItems = function() {
    var self = this;
    var grand_total = 0
    self.iterate(function(key,obj){
        var quantity = obj.qty;
        grand_total = grand_total + quantity;
    });
    return grand_total;
}

CartCollection.prototype.getTotalCost = function() {
    var self = this;
    var grand_total = 0.00
    self.iterate(function(key,obj){
        var initial_charge = parseFloat(obj.data.initial_charge);
        var additional_charge = parseFloat(obj.data.additional_charge);
        var quantity = obj.qty;
        var cost_price = self.getItemTotalCost(quantity,initial_charge,additional_charge);
        grand_total = grand_total + cost_price;

    });
    return grand_total;
}

CartCollection.prototype.getItemTotalCost = function(qty,initial_charge,additional_charge) {
    var self = this;
    var grand_total = 0.00

    if(qty == 1){
        grand_total = initial_charge * qty;
    }
    else{//Will always be greater
        var first_charge = 1 * initial_charge;
        var second_charge = 0.00;
        var ball_qty = qty - 1;
        if(additional_charge != 0){
            second_charge = ball_qty * additional_charge;
        }
        else{
            second_charge = ball_qty * initial_charge;
        }
        grand_total = first_charge + second_charge;
    }

    return grand_total;
}

/*******************************************************************************
 *            END OF SHOPPING CART COLLECTIONS CLASS
 ******************************************************************************/


/*
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Sales = {
    _cart: new CartCollection(),

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;

        self._cart.registerCallback('add', function(key, obj) {
            self.refreshCartUI();
        });

        self._cart.registerCallback('remove', function(key) {
            self.refreshCartUI();
        });

        /*Add and Remove from cart*/
        $('#add-to-cart-btn').click(function () {
            //self.updateInsurance();
            self.updateCart('add');
        });
        $('#remove-from-cart-btn').click(function () {
            //self.updateInsurance();
            self.updateCart('remove');
        });
        /***********************************/

        $('#bill-me-now-btn').click(function () {
            self.saveSale();
        });

        $('#cancel-btn').click(function () {
            document.getElementById('students-purchase-form').reset();
            self._cart.clear();
            $("#cart").html('');
            //self.creditCheck();
        });
    },

    updateCart:function (action) {
        var self = this;
        var id_s = $("#select_items").val();
        var quantity_limit = parseInt(global_item_data[id_s]['quantity_limit']);
        var name = global_item_data[id_s]['description'];
        if(!isNaN(quantity_limit) && action == 'add'){
            var obj = self._cart.get(id_s);
            if(obj != null){
                var cur_qty = obj.qty;
                var cur_qty_tobe = cur_qty + 1;
                if(cur_qty_tobe < quantity_limit){

                }
                else if(cur_qty_tobe == quantity_limit){

                }
                else{
                    alert("Sorry, "+name+" has a quantity limit of "+quantity_limit+", you can't add more than the expected quantity.");
                    return false
                }
            }
        }
        //Validate the item's quantity check


        if(!id_s){
            return false;
        }
        if (action == 'add') {
            //for(var i in ids){
                var id = id_s;
                var name = global_item_data[id]['description'];
                var initial_charge = parseFloat(global_item_data[id]['initial_charge']);
                var additional_charge = parseFloat(global_item_data[id]['additional_charge']);
                //var quantity_limit = global_item_data[id]['quantity_limit'];

                //console.log(unit_price);
                //console.log(typeof  unit_price);

                self._cart.add(id,{
                    id:id,
                    name:name,
                    initial_charge:initial_charge,
                    additional_charge:additional_charge,
                    quantity_limit:quantity_limit
                });
            //}
        }
        else{
            //for(var i in ids){
               // var id = ids[i];
             var id = id_s;
                self._cart.remove(id);
            //}
        }
    },

    refreshCartUI:function(){
        var self = this;

        $("#cart").html('');
        self._cart.iterate(function(key, obj){
            var id = key
            var name = obj.data.name;
            var initial_charge = parseFloat(obj.data.initial_charge);
            var additional_charge = parseFloat(obj.data.additional_charge);
            var quantity = obj.qty;
            var cost_price = self._cart.getItemTotalCost(quantity,initial_charge,additional_charge);

            var tr = $("<tr />").attr('data-id',key);
            tr.append($("<td />").html(name+" &nbsp;"))
                .append($("<td />").html(quantity+" &nbsp;"))
                .append($("<td />").html(cost_price+" &nbsp;"));

            $("#cart").append(tr);
        });

        var grand_total = self._cart.getTotalCost();
       // $("#form #cost").val(jLib.formatNumber(grand_total,'money'));

       // self.creditCheck();

    },


    saveSale:function () {
        var self = this;

        var total_cost = self._cart.getTotalCost();
        if(total_cost == 0){
            alert("There are no items to purchase.");
            return false;
        }

        var r=window.confirm("Are you sure you want to purchase these items ?");
        if (!r){
            return false;
        }

        var params = {
            'index_number':$("#index_number").val(),
            'academic_year':$("#current_academic_yr").val(),
            'trans_type_to_use':'item_purchase'
        }
        var r = self._cart.createSaleItemModelData(params);
        var data = {
            'Fee':r
        };

        var url = $('#do-payment-url').val();
        var query = 'data=' + encodeURIComponent(JSON.stringify(data));

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    /* Alert the user that the server response*/
                    alert(txt);
                    //Reset the form
                    $('#cancel-btn').click();
                    window.location = $("#payment-url").val();

                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    alert(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
            }
        });
    }

};

/* when the page is loaded */
$(document).ready(function () {
    Sales.init();
});